package com.gugee.tiktok.web.service;


import com.gugee.tiktok.web.dto.HelpCenterArticleDto;
import com.gugee.tiktok.web.dto.HelpCenterArticleSummaryDto;
import com.gugee.tiktok.web.dto.HelpCenterMenuDto;
import com.gugee.tiktok.web.model.mysql.HelpArticle;
import com.gugee.tiktok.web.model.mysql.HelpMenu;
import com.gugee.tiktok.web.model.mysql.HelpMenuArtcleStatic;
import com.gugee.tiktok.web.repository.HelpArticleRepository;
import com.gugee.tiktok.web.repository.HelpMenuRepository;
import com.xiguaji.boot.toolkit.jdbc.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Component
public class HelperServiceImpl implements HelperService {

    @Autowired
    HelpArticleRepository helpArticleRepository;

    @Autowired
    HelpMenuRepository helpMenuRepository;

    @Autowired
    HelpCenterArticleDto.HelpCenterArticleDtoMapper articleDtoMapper;
    @Autowired
    HelpCenterMenuDto.HelpCenterMenuDtoMapper menuDtoMapper;

    private final String artcleUrlPath="/help-art/";
    private final String artclesUrlPath="/help-arts/";

    /**
     * 查询菜单
     *
     * @return
     */
    @Override
    public List<HelpCenterMenuDto> findAllHelpCenterMenuDtos() {
        /**
         * todo 请求量大的时候，每次都要查询数据库，数据库服务器压力会增加，
         * 由于菜单文章由另一个服务管理，故可用分布式缓存解决，由管理服务完成缓存数据更新
         */
        List<HelpMenu> helpMenus=helpMenuRepository.findALLOrderByTypeAndOrderByMenuSortDesc();
        List<HelpMenuArtcleStatic> articleStaticList=helpArticleRepository.findHelpArticlesStatic();
        //菜单与菜单下文章数量的映射
        HashMap<Long,HelpMenuArtcleStatic> menuArtcleMap=new HashMap<>();
        //转换hash,后续设置url地址做为逻辑条件
        articleStaticList.forEach(articleStatic->{
            menuArtcleMap.put(articleStatic.getMenuId(),articleStatic);
        });

        List<HelpCenterMenuDto> rst=new ArrayList<>(32);
        //一级菜单的HASH引用
        HashMap<Long,HelpCenterMenuDto> firstRef=new HashMap<>();
        //利用已排好序的rst
        helpMenus.forEach(menu->{
            HelpCenterMenuDto menuDto= menuDtoMapper.mapperDto(menu);
            //一级菜单
            if(menu.getType()==0){
                rst.add(menuDto);
                firstRef.put(menuDto.getId(),menuDto);
            }
            //二级菜单关联至一级菜单
            if(menu.getType()==1){
                //是否有父菜单存在
                if(firstRef.containsKey(menuDto.getParentId())){
                    //将子菜单挂至父菜单
                    firstRef.get(menuDto.getParentId()).putSubMenu(menuDto);
                };
            }
            //设置菜单的url
            setMenuUrl(menuDto,menuArtcleMap);
        });
        return rst;
    }
    @Override
    //查询文章列表
    public List<HelpCenterArticleSummaryDto> findAllArticlesSummary(Long menuId) {

        int totals=helpArticleRepository.countAllByMenuId(menuId);

        List<HelpCenterArticleSummaryDto> articles = helpArticleRepository.findAllArticlesSummary(menuId);
        articles.forEach(summary->{
                    summary.setUrl(artcleUrlPath+summary.getId()+"/"+summary.getUrl());
                }
        );

        return articles;
    }
    @Override
    //查询文章列表 分页
    public Page<HelpCenterArticleSummaryDto> findAllArticlesSummary(Long menuId, int pageNumber, int pageSize) {
        if(pageNumber<=0){
            pageNumber=1;
        }
        if(pageSize<=0){
            pageSize=10;
        }
        int totals=helpArticleRepository.countAllByMenuId(menuId);
//        String contextPath = request.getScheme() +"://" + request.getServerName()  + ":" +request.getServerPort() +request.getContextPath();
        List<HelpCenterArticleSummaryDto> articles = helpArticleRepository.findAllArticlesSummaryByMenuId(menuId,pageNumber,pageSize);
        articles.forEach(summary->{
            summary.setUrl(artcleUrlPath+summary.getId()+"/"+summary.getUrl());
           }
        );

        Page<HelpCenterArticleSummaryDto> pageList=new Page<>(articles,pageNumber,pageSize,totals/pageSize+1,totals);

        return pageList;
    }

    @Override
    public HelpArticle findHelpCenterArticleDtoById(Long articleId) {
        Optional<HelpArticle> optionalHelpArticle= helpArticleRepository.findById(articleId);
        return optionalHelpArticle.orElse(null);
    }

    private void setMenuUrl(HelpCenterMenuDto menu,HashMap<Long,HelpMenuArtcleStatic> menuArtcleMap){
        if(menu==null){
            return;
        }
        if(menuArtcleMap==null|| menuArtcleMap.isEmpty()){
            menu.setUrl("#");
            return;
        }
        //该菜单下有挂文章且文章数大于1
        if(menuArtcleMap.containsKey(menu.getId())){
            HelpMenuArtcleStatic tmp=menuArtcleMap.get(menu.getId());
            //文章不止一篇，设置为文章列表artcles UrlPath
            if( tmp.getArticles()>1){
                menu.setUrl(artclesUrlPath+tmp.getMenuId());
            }
            //文章只有一篇，设置为文章artcle UrlPath
            if( tmp.getArticles()==1){
                menu.setUrl(artcleUrlPath+tmp.getId()+"/"+tmp.getUrl());
            }
            if( tmp.getArticles()==0){
                menu.setUrl("#");
            }
            return;
        }
            menu.setUrl(null);
    }
}
